import React, { Component, Fragment } from 'react'
import {getArtList,delArt} from 'api'
import {limitWord} from 'utils'
import { Card,Button,Table,Tag,Tooltip,Image,message,Modal } from 'antd'
import {DownloadOutlined,ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import XLSX from 'xlsx'
import './style.css'
export default class ArtList extends Component {
  constructor () {
    super()
    this.state = {
      data: [["序号","标题","文章描述","内容","作者","创建时间","封面图片","阅读次数"]], /* Array of Arrays e.g. [["a","b"],[1,2]] */
      columns : [
        {
          title: '标题',
          dataIndex: 'title',
          key: 'title',
        },
        {
          title: '文章描述',
          dataIndex: 'desc',
          render: (text,record,index)=>{
             return (
              <Tooltip title={text}>
                <span>
                  {limitWord(text)}
                </span>
              </Tooltip>
             )
          },
          key: 'desc',
        },
        {
          title: '阅读次数',
          dataIndex: 'readCount',
          render:(text,record,index)=> {
             return (
                <Tag 
                color={
                  text>400?'red':'green'
                }
                >
                  {text}
                </Tag>
             )
          },
          key: 'readCount',
        },
        {
          title: '作者',
          dataIndex: 'auther',
          key: 'auther',
        },
        {
          title: '创建时间',
          dataIndex: 'createAt',
          render: (text)=> {
            return (
              <span>
                {moment().format('YYYY-MM-DD')}
              </span>
            )
          },
          key: 'createAt',
        },
        {
          title: '封面图片',
          dataIndex: 'picture',
          render: (text) =>{
            return (
            <Image src={text}/>
            )
          },
          key: 'picture',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          render: (text,record) => {
            return (
              <Fragment>
                <Button onClick={()=>this.props.history.push(`/admin/artEdit/${record.id}`)} type='ghost' size='small' style={{ marginRight: 10,borderColor:'skyblue',color:'skyblue' }}>编辑</Button>
                <Button type='ghost' danger size='small' onClick= {() => {this.fetchDelArt(record.id)}}>删除</Button>
              </Fragment> 
            )
          },
          key: 'operation',
        },
      ],
      artList: [],
      current: 1,
      total: 0,
      pageSize:10
    }
  }
  render() {
    return (
      <Fragment>
        <div className="wrapper">
          <Card 
          title="文章列表" 
          bordered={false}
          extra={
            <Fragment>
              <Button
              type='ghost'
              danger
              icon={<DownloadOutlined/>}
              onClick = {()=> { this.exportFile() }}
              >导出excel</Button>
            </Fragment>
          }
          >
            <Button type='default' style={{ marginBottom: 20 }} onClick ={ ()=> this.props.history.push('/admin/artAdd') }>添加文章</Button>
            {/* 用表格渲染数据*/}
            <Table
             dataSource={this.state.artList}
              columns={this.state.columns}
              pagination = {
                {
                total: this.state.total,
                current: this.state.current,
                pageSize: this.state.pageSize,
                onChange: (current,pageSize) => {
                   this.setState({
                     current,
                     pageSize
                   },() => {
                      this.fetchArtList()
                   })
                }
              }}
              />;
          </Card>
        </div>
      </Fragment>
    )
  }
  componentDidMount () {
    this.fetchArtList()
  }
  // 获取文章列表
  fetchArtList = () => {
    getArtList({
      current: this.state.current,
      pageSize: this.state.pageSize
    }).then(res=>{
      if(res.data.code === '200') {
        this.setState({
          artList: res.data.data.lists,
          current: res.data.data.current,
          total: res.data.data.total
        })
      }
    })
  }
  // 删除文章
  fetchDelArt = (id) =>{
    const _this = this
    Modal.confirm({
      title: '确认删除该篇文章吗?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        delArt(id).then(res => {
          if (res.data.code === '200') {
            message.success(res.data.msg,2,()=>{
              _this.props.history.go(0)
            })
          }
        })
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }
  // 导出文章列表
  exportFile = () => {
    /* convert state to workbook */
    let exportList = this.state.data
    this.state.artList.forEach(art=>{
      exportList.push(Object.values(art))
    })
		const ws = XLSX.utils.aoa_to_sheet(exportList);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
		/* generate XLSX file and send to client */
		XLSX.writeFile(wb, "sheetjs.xlsx")
	};
}
